package com.shenzhen.horselive.ui.fragment;

import android.Manifest;
import android.content.ContentProviderOperation;
import android.content.Intent;
import android.location.Location;
import android.location.LocationManager;
import android.location.OnNmeaMessageListener;
import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.flqy.baselibrary.utils.GlideHelper;
import com.flqy.baselibrary.utils.T;
import com.hjq.permissions.OnPermission;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.mozillaonline.providers.DownloadManager;
import com.shenzhen.horselive.R;
import com.shenzhen.horselive.User;
import com.shenzhen.horselive.api.ApiFactory;
import com.shenzhen.horselive.api.ApiService;
import com.shenzhen.horselive.base.BaseFragment;
import com.shenzhen.horselive.beans.CityCodeBean;
import com.shenzhen.horselive.beans.CityMasterBaseBean;
import com.shenzhen.horselive.beans.CommResponseBean;
import com.shenzhen.horselive.beans.HongBaoBean;
import com.shenzhen.horselive.beans.HongBaoRangeBean;
import com.shenzhen.horselive.beans.MapRedPackageBean;
import com.shenzhen.horselive.beans.OpenRedBean;
import com.shenzhen.horselive.databinding.FragmentOpenHongBaoBinding;
import com.shenzhen.horselive.network.SchedulersCompat;
import com.shenzhen.horselive.presenter.LoadingViewObserver;
import com.shenzhen.horselive.presenter.ViewObserver;
import com.shenzhen.horselive.ui.activity.AddAppActivity;
import com.shenzhen.horselive.ui.activity.AppRedpackageActivity;
import com.shenzhen.horselive.ui.activity.AuctionDetailsActivity;
import com.shenzhen.horselive.ui.activity.BroadcastRedpacketsActivity;
import com.shenzhen.horselive.ui.activity.EmptyActivity;
import com.shenzhen.horselive.ui.activity.HongBaoDetailsActivity;
import com.shenzhen.horselive.ui.activity.MyCityLordActivity;
import com.shenzhen.horselive.ui.activity.MyCityLordAuctioningActivity;
import com.shenzhen.horselive.ui.activity.SendReciRedDetailsActivity;
import com.shenzhen.horselive.ui.activity.ShareActivity;
import com.shenzhen.horselive.ui.dialog.GiveRedpackageDialog;
import com.shenzhen.horselive.ui.dialog.OpenHongBaoDialog;
import com.shenzhen.horselive.utils.DialogManager;
import com.shenzhen.horselive.utils.GetJsonDataUtil;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.tencent.map.geolocation.TencentLocation;
import com.tencent.map.geolocation.TencentLocationListener;
import com.tencent.map.geolocation.TencentLocationManager;
import com.tencent.map.geolocation.TencentLocationRequest;
import com.tencent.tencentmap.mapsdk.maps.CameraUpdateFactory;
import com.tencent.tencentmap.mapsdk.maps.TencentMap;
import com.tencent.tencentmap.mapsdk.maps.model.BitmapDescriptor;
import com.tencent.tencentmap.mapsdk.maps.model.BitmapDescriptorFactory;
import com.tencent.tencentmap.mapsdk.maps.model.Circle;
import com.tencent.tencentmap.mapsdk.maps.model.CircleOptions;
import com.tencent.tencentmap.mapsdk.maps.model.IOverlay;
import com.tencent.tencentmap.mapsdk.maps.model.LatLng;
import com.tencent.tencentmap.mapsdk.maps.model.Marker;
import com.tencent.tencentmap.mapsdk.maps.model.MarkerOptions;

import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link OpenHongBaoFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class OpenHongBaoFragment extends BaseFragment {

    public OpenHongBaoFragment() {
        // Required empty public constructor
    }
    public static OpenHongBaoFragment newInstance() {
        OpenHongBaoFragment fragment = new OpenHongBaoFragment();
//        Bundle args = new Bundle();
//        args.putString(ARG_PARAM1, param1);
//        args.putString(ARG_PARAM2, param2);
//        fragment.setArguments(args);
        return fragment;
    }
    FragmentOpenHongBaoBinding  binding;
    @Override
    protected View getContentView(LayoutInflater inflater, ViewGroup viewGroup) {
        binding = FragmentOpenHongBaoBinding.inflate(getLayoutInflater(),viewGroup,false);
        initViews();
        return binding.getRoot();
    }

    private TencentLocationManager   locationManager;
    TencentMap  tencentMap;
    private RxPermissions  rxPermissions ;
    //初始化
    private void initViews() {
        rxPermissions = new RxPermissions(getActivity());
        tencentMap = binding.mapView.getMap();
//       tencentMap.getUiSettings().setRotateGesturesEnabled(false);
//        setRotateGesturesEnabled(boolean flag)
        //第一次定位
        locationManager = TencentLocationManager.getInstance(getContext());
        binding.imgRefresh.setOnClickListener(onClickListener);
        //按钮点击事件
        binding.linerCity.setOnClickListener(onClickListener);
        binding.imgSendRed.setOnClickListener(onClickListener);
        binding.linerKuozhang.setOnClickListener(onClickListener);

        //标记记号的点击事件
        tencentMap.setOnMarkerClickListener(new TencentMap.OnMarkerClickListener() {
                    @Override
                    public boolean onMarkerClick(Marker marker) {
                       MapRedPackageBean  bean = (MapRedPackageBean) marker.getTag();
                       if (bean!=null)
                       {
                           openDialog(bean,marker);
                       }
                        return true;
                    }
                });
        tencentMap.addOnMapLoadedCallback(new TencentMap.OnMapLoadedCallback() {
            @Override
            public void onMapLoaded() {
                //地图加载完成之后定位
                location();
            }
        });

    }

    //打开红包
    private void openDialog(MapRedPackageBean bean, Marker marker) {
        OpenHongBaoDialog  dialog = new OpenHongBaoDialog(getContext(), bean);
        dialog.setOnOpenClick(new OpenHongBaoDialog.OnOpenClick() {
            @Override
            public void onOpen() {
                //点击打开红包
                if (myprovincecode==null||mycitycode==null||myareaCode==null)
                {
                    showToast("无法查询到城市的code码");
                    return;
                }
                ApiFactory.getApiService().openRed(User.get().getMyInfo().getToken()
                        ,bean.getId()+"",bean.getType()+"",myprovincecode,
                        mycitycode,myareaCode
                ).compose(SchedulersCompat.applyIoSchedulers())
                        .safeSubscribe(new LoadingViewObserver<OpenRedBean>(OpenHongBaoFragment.this) {
                            @Override
                            protected void onNextInActive(OpenRedBean openRedBean) {
                                dialog.dismiss();
                                marker.remove();
                                if (openRedBean.isSuccess())
                                {
//                                    maxReceive	是	boolean	是否进入领取上限
//                                    receiveOut	是	boolean	是否被领完
//                                    alreadyReceive	是	boolean	是否领取过
                                    //直接到红包详情
                                    if ("true".equals(openRedBean.getData().getMaxReceive())||"true".equals(openRedBean.getData().getReceiveOut())
                                    ||"true".equals(openRedBean.getData().getAlreadyReceive())
                                    )
                                    {
                                        String  notice = "";
                                        if ("true".equals(openRedBean.getData().getMaxReceive()))
                                        {
                                            notice ="已经达到领取上限";
                                        }

                                        if ("true".equals(openRedBean.getData().getReceiveOut()))
                                        {
                                            notice ="红包已经被领完";
                                        }
                                        if ("true".equals(openRedBean.getData().getAlreadyReceive()))
                                        {
                                            notice ="已经领取过该红包";
                                        }
                                        DialogManager.getInstance().showCommentDialog(getContext(),"",notice);
                                    }
                                    else
                                    {
                                        if (!TextUtils.isEmpty(openRedBean.getData().getId()))
                                            HongBaoDetailsActivity.start(getContext(),"1",openRedBean.getData().getId()+"",false);
                                    }

                                }else
                                {
                                    showToast(openRedBean.getErrMessage());
                                }
                            }
                        });
            }
        });
        dialog.show();
        }


    private  void  location()
    {
        //单点定位
        String[] permissions = {
                Permission.ACCESS_COARSE_LOCATION,
                Permission.ACCESS_FINE_LOCATION,
                Permission.READ_PHONE_STATE,
                Permission.WRITE_EXTERNAL_STORAGE,
        };

        XXPermissions.with(getActivity())
                .permission(permissions)
        .request(new OnPermission() {
            @Override
            public void hasPermission(List<String> granted, boolean all) {
                if (all)
                {

                    TencentLocationRequest request = TencentLocationRequest.create();
                    request.setRequestLevel(3)//包含区域信息
                            .setAllowGPS(true)
                            .setIndoorLocationMode(true)
                            .setInterval(5000)
                    ;
                    int error = locationManager.requestLocationUpdates(request, locationListener,Looper.getMainLooper());
                    if (error == 0)
                        Log.e("addr","注册位置监听器成功！");
                    else
                        Log.e("addr","注册位置监听器失败！");
//                    locationManager.requestSingleFreshLocation(null, locationListener, Looper.getMainLooper());
                }
            }

            @Override
            public void noPermission(List<String> denied, boolean quick) {

            }
        });
        ;


    }




    long  mlasttime;
    private View.OnClickListener  onClickListener= new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            long nowtime = System.currentTimeMillis();
            if ((nowtime-mlasttime)/1000<1)
            {
                return;
            }
            switch (v.getId())
            {
                case R.id.img_refresh:
                    //手动定位
                  location();
                    break;
                case R.id.liner_city:
                    //我的城主
//                    startActivity(new Intent(getContext(), MyCityLordActivity.class));

                    break;
                case R.id.img_send_red:
                    sendRed();
                    break;
                case R.id.liner_kuozhang:
                    startActivity(new Intent(getContext(), ShareActivity.class));
                    break;
            }

        }
    };

    //发红包
    GiveRedpackageDialog  dialog;
    private void sendRed() {
        if (dialog==null)
        {
            dialog =  new GiveRedpackageDialog(getContext());
            dialog.setOnItemClick(new GiveRedpackageDialog.OnItemClick() {
                @Override
                public void onClick(int positon) {
                 if (positon==1)
                 {
                     //广播红包
                     startActivity(new Intent(getContext(), BroadcastRedpacketsActivity.class));
                 }
                 else if (positon==2)
                 {
                     //优惠券红包
                     EmptyActivity.start(getContext(),"发优惠券");
                 }
                 else if (positon==3)
                 {
                     startActivity(new Intent(getContext(), AppRedpackageActivity.class));
                 }
                }
            });

        }
        dialog.show();

    }


    private TencentLocationListener  locationListener = new TencentLocationListener() {
        @Override
        public void onLocationChanged(TencentLocation tencentLocation, int i, String s) {
            //获取到定位信息
            locationManager.removeUpdates(locationListener);
            if(i == TencentLocation.ERROR_OK){
                //主动关闭定位,实现单次定位
                tencentMap.clearAllOverlays();
                //获取红包
                getHongBaoList(tencentLocation.getLatitude(),
                        tencentLocation.getLongitude(),
                        tencentLocation.getProvince(),
                        tencentLocation.getCity(),
                        tencentLocation.getDistrict()
                );
                //获取范围
                getRange(tencentLocation.getLatitude(),tencentLocation.getLongitude());

            }
            else
            {
                Log.v("map",i+s);
            }

        }

        @Override
        public void onStatusUpdate(String s, int i, String s1) {

        }
    };

    private void getRange(double latitude, double longitude) {
        ApiFactory.getApiService().getHongBaoRange(User.get().getMyInfo().getToken())
                .compose(SchedulersCompat.applyIoSchedulers())
                .safeSubscribe(new ViewObserver<HongBaoRangeBean>(this) {
                    @Override
                    protected void onNextInActive(HongBaoRangeBean hongBaoRangeBean) {
                        if (hongBaoRangeBean.isSuccess())
                        {
                      String   mile = hongBaoRangeBean.getData();
                      binding.tvMiles.setText(String.format("%s米\n扩张收红包范围",mile));
                     LatLng latLng = new LatLng(latitude,longitude);
                     Circle  circle =   tencentMap.addCircle(new CircleOptions().
                        // 圆心
                                center(latLng).
                        // 半径
                                radius(Double.parseDouble(mile)).
                        // 圆的填充色
                                fillColor(0x20000000).
                        // 描边的颜色
                                strokeColor(0x979797).
                        // 描边宽度
                                strokeWidth(0.5f).
                        // 可点击性
                                clickable(false).
                        // 可见性
                                visible(true).
                        // 层级
                                zIndex(1)
               );
                  List<IOverlay>  list =  new ArrayList<>();
                  list.add(circle);
                 tencentMap.moveCamera(CameraUpdateFactory.newCameraPosition(
                                    tencentMap.calculateZoomToSpanLevel(
                                            list, null,
                                            0, 0, 0, 0)));
                        }else
                        {
                            showToast(hongBaoRangeBean.getErrMessage());
                        }
                    }
                });

    }

    private   String  mycitycode;
    private  String  myprovincecode;
    private  String  myareaCode;
    //根据经纬度获取红包列表
    private void getHongBaoList(double latitude, double longitude, String province, String city, String district) {
        //先根据省市区获取code码
        if (province==null||city==null||district==null)
            return;
        String  provincecode =null;
        String  citycode= null;
        String  areaCode = null;
        if (GetJsonDataUtil.getInstance().getCityCodeBeanList()==null)
        {
            //无法获取到citycode
            showToast("citycode没有初始化成功");
            return;
        }
        for (CityCodeBean b: GetJsonDataUtil.getInstance().getCityCodeBeanList()
             ) {
            if (province.equals(b.getName()))
            {
                provincecode = b.getCode();
                for (CityCodeBean.CityListBean cityListBean:b.getCityList()
                     ) {
                    if (city.equals(cityListBean.getName()))
                    {
                        citycode =cityListBean.getCode();
                        for (CityCodeBean.CityListBean.AreaListBean  arebean:cityListBean.getAreaList()
                             ) {
                            if (district.equals(arebean.getName()))
                            {
                                areaCode =  arebean.getCode();
                                break;
                            }
                        }
                        break;
                    }
                }
                break;
            }
        }

        if (areaCode==null||citycode==null)
        {
            showToast("查询不到当地的code码");
            return;
        }
        //获取城主的基本信息
        getCityMasterBase(areaCode,city,district);
        myareaCode = areaCode;
        mycitycode = citycode;
        myprovincecode = provincecode;
        //查询红包列表
        ApiFactory.getApiService().getHongBaoList(User.get().getMyInfo().getToken()
        ,longitude+"",latitude+"",citycode,areaCode
        ).compose(SchedulersCompat.applyIoSchedulers())
                .safeSubscribe(new LoadingViewObserver<HongBaoBean>(this) {
                    @Override
                    protected void onNextInActive(HongBaoBean hongBaoBean) {
                        if (hongBaoBean.isSuccess())
                        {
                          //添加标记点
                          addMark(hongBaoBean.getData());

                        }else
                        {
                            showToast(hongBaoBean.getErrMessage());

                        }
                    }
                });

    }

    private void getCityMasterBase(String areaCode,String  city,String area) {
        ApiFactory.getApiService().findCityMasterBase(User.get().getMyInfo().getToken(),areaCode)
                .compose(SchedulersCompat.applyIoSchedulers())
                .safeSubscribe(new ViewObserver<CityMasterBaseBean>(this) {
                    @Override
                    protected void onNextInActive(CityMasterBaseBean cityMasterBaseBean) {
                        if (cityMasterBaseBean.isSuccess())
                        {
                            if (cityMasterBaseBean.getData()!=null)
                            {

                                int  status = cityMasterBaseBean.getData().getStatus();
                                binding.linerCity.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {

                                        if (status==1||status==2)
                                        {
                                            //竞价中
//                                            MyCityLordAuctioningActivity.start(getContext(),areaCode);
                                            AuctionDetailsActivity.start(getContext(),areaCode,1);
                                        }
                                        else
                                        {
                                            //待开放和已经有城主了
                                           MyCityLordActivity.start(getContext()
                                                ,areaCode);
                                        }
                                    }
                                });

//                                0待开放 1第一次竞价中 2第二次竞价中 3流拍中 4已锁定
                              switch (cityMasterBaseBean.getData().getStatus())
                              {
                                  case 0:
                                      binding.tvCityMasterHead.setText("待开放");
                                      binding.linerCityMasterHead.setVisibility(View.GONE);
                                      break;
                                  case 1:
                                  case 2:
                                  case 3:
                                      binding.tvCityMasterHead.setText("竞拍中");
                                      binding.linerCityMasterHead.setVisibility(View.GONE);
                                      break;
                                  case 4:
                                      binding.linerCityMasterHead.setVisibility(View.VISIBLE);
                                      //名字展示
                                      String  name = cityMasterBaseBean.getData().getUserName();
                                      binding.tvCityMasterHead.setText("城主："+name.charAt(0)+"**");
                                      GlideHelper.loadAdvertImage(cityMasterBaseBean.getData().getHeadImg(),binding.imgCityUserHead);
                                      break;

                              }



//                              binding.tvCityMasterHead.setText("城主："+cityMasterBaseBean.getData().getUserName());
//                            GlideHelper.loadAdvertImage(cityMasterBaseBean.getData().getHeadImg(),binding.imgCityUserHead);
                            }
                        }else
                        {
                            showToast(cityMasterBaseBean.getErrMessage());
                        }
                    }
                });
    }
    //地图添加标记点
    private void addMark(List<MapRedPackageBean> data) {
        for (int i = 0; i < data.size(); i++) {
            MapRedPackageBean  bean = data.get(i);
//            1：平台红包，2：应用红包，3：广播红包
            BitmapDescriptor
                    custom = BitmapDescriptorFactory.fromResource(tencentMap.getMapContext(),R.mipmap.ico_map_red_bao);
            if (bean.getType()==1)
            {
                //平台红包
                custom = BitmapDescriptorFactory.fromResource(tencentMap.getMapContext(),R.mipmap.ico_pingtai_red_bao);
            }
            LatLng position = new LatLng(Double.parseDouble(bean.getLat()),Double.parseDouble(bean.getLng()));
            tencentMap.addMarker(new MarkerOptions(position)
                    .icon(custom)
                    .zIndex(2)
                    .fastLoad(false)
                    .tag(bean)
            );

        }

    }
    @Override
    public void onResume() {
        super.onResume();
        binding.mapView.onResume();
    }

    @Override
    public void onStart() {
        super.onStart();
        binding.mapView.onStart();
    }

    @Override
    public void onPause() {
        super.onPause();
        binding.mapView.onPause();
    }

    @Override
    public void onStop() {
        super.onStop();
        binding.mapView.onStop();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        binding.mapView.onDestroy();
    }

    @Override
    public void initImmersionBar() {

    }
}